home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Pointer to Functions and Calls thereof??
- Date: 17 Apr 1996 07:02:30 -0700
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4l2tlmINN822@keats.ugrad.cs.ubc.ca>
- References: <Dq01Ft.Dqn@latcs1.lat.oz.au>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <Dq01Ft.Dqn@latcs1.lat.oz.au>,
- Eric Woelkerling <woelkerl@lion.cs.latrobe.edu.au> wrote:
- > Hi! Can anybody fill me in as to how to get a pointer to a function
- >and then use this to do the call?? I have a situation where a particular function
-
- Wow. An actual _on topic_ question for comp.lang.c. Amazing!
-
- >will be selected from a set of functions and used throughout my entire code,
- >but the function selected will depend on the runtime selection by thge user..
- >
- >so far.. I have got as far as..
- >
- >
- > void func1(void){naughty bits}
- > void func2(void){naughty bits}
- >
- > void main(void)
- > { void *a[1];
- >
- > a[1]=func1;
- > a[2]=func2;
- >
- > (*a[1])();
- > }
- >
- > Is there something obvious I am missing here?? I am on a PC and using
- >borland c++ compiler...
-
- You are missing the fact that the object a has been declared as a one-membered
- array of type (void *). It is not a function pointer. In fact, it can't even be
- used to store function pointers, since it is illegal in C to covert between
- void * and function pointers.
-
- Secondly, when you declare an array TYPE a[1], you may only access elements
- a[0] and a[1]. Accessing element a[2] is not allowed. The C Standard calls it
- undefined behavior.
-
- To store function pointers, you must use an object that has a compatible type.
- In your case, the two functions have a new-style empty parameter list and
- return void. To declare a compatible function pointer, you would use a
- declaration like:
-
- void (* funptr)(void);
-
- The first parentheses override the precedence of the (void) parameter list.
- Without them, you would be declaring a function returning void *, not a
- pointer to a function returning void.
-
- You then assign to funptr in a straightforward manner:
-
- funptr = func1;
-
- Function pointers are treated specially by C. There is no need to use a
- dereference operator when you want to call through them. To call the function
- pointed at by funptr, you just do:
-
- funptr();
-
- That's it.
-
- By the way, if you want an array of two functions, you can declare this:
-
- void (* funarray[3])(void);
-
- > If you can help, please mail me directly Thanks!
-
- Okay, but please go to the newsgroup. It may be worthwhile.
- --
- I'm not really a jerk, but I play one on Usenet.
-